# common.py
from __future__ import with_statement

import sys
import logging
import os

READINGS = '/var/www/readings.json'
#READINGS = 'readings.json'

def setup_logging():
    directory = '' if sys.platform == 'win32' else './'
    filename = directory+sys.argv[0]+'.log'
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)s %(message)s',
                        filename=filename)
    logging.debug('Start '+sys.argv[0]+' pid '+str(os.getpid()))
    # with open(sys.argv[0]+'.pid.'+str(os.getpid()),'w') as f:
    #     f.write('foobar')

def to_amps(circuit, count):
    if circuit < 3:
        return 0 if count == '0' else 0.0289 * int(count,16) + 0.03565
    else:
        return 0 if count == '0' else 0.0043 * int(count,16) + 0.0287

def get_readings():
    with open(READINGS, 'r') as f:
        l = f.read().encode()
    try:
        readings = json.loads(l)
    except:
        logging.debug('json failure: '+"'"+l+"'")
        readings = {u'datetime': time.ctime(),
                    u'volts': 0.0,
                    u'watts1': 0.0, u'watts2': 0.0,
                    u'raw': ["0"]*32}
    raw = readings[u'raw'][7:] # we won't actually reference raw[0]
    volts = round(readings[u'volts'],2)

    for i in range(1,25):
        watts[i] = common.to_amps(i, raw[i]) * volts

    readings[u'watts'] = watts[1:]

    return readings


